<template>
  <div class="actions-container">
    <div class="header">
      <h2>用户行为管理</h2>
      <!-- <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增行为
        </el-button>
      </div> -->
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="行为类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择类型"
            clearable
            style="width: 120px"
          >
            <el-option label="收藏" :value="1" />
            <el-option label="浏览" :value="2" />
            <el-option label="想要" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="actions"
        stripe
        style="width: 100%"
        :row-key="(row) => row.id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="productName" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="行为类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getActionTypeTag(row.type)">
              {{ getActionTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="行为时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(row)">查看</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 行为详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="行为详情"
      width="500px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentAction" class="action-detail">
        <div class="detail-item">
          <label>用户ID：</label>
          <span>{{ currentAction.userId }}</span>
        </div>
        <div class="detail-item">
          <label>商品名称：</label>
          <span>{{ currentAction.productName }}</span>
        </div>
        <div class="detail-item">
          <label>行为类型：</label>
          <el-tag :type="getActionTypeTag(currentAction.type)">
            {{ getActionTypeText(currentAction.type) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>行为时间：</label>
          <span>{{ formatDate(currentAction.createTime) }}</span>
        </div>
      </div>
    </el-dialog>

    <!-- 新增行为对话框 -->
    <el-dialog
      v-model="addVisible"
      title="新增行为"
      width="500px"
      :before-close="handleAddClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model.number="addForm.userId"
            placeholder="请输入用户ID"
            type="number"
          />
        </el-form-item>
        <el-form-item label="商品ID" prop="productId">
          <el-input
            v-model.number="addForm.productId"
            placeholder="请输入商品ID"
            type="number"
          />
        </el-form-item>
        <el-form-item label="行为类型" prop="type">
          <el-select
            v-model="addForm.type"
            placeholder="请选择行为类型"
            style="width: 100%"
          >
            <el-option label="收藏" :value="1" />
            <el-option label="浏览" :value="2" />
            <el-option label="想要" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddClose">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/date'
import request from '@/utils/request'

// 定义Interaction类型
interface Interaction {
  id: number
  userId: number
  productId: number
  productName?: string
  type: number // 1: 收藏, 2: 浏览, 3: 想要
  createTime: string
}

// 响应式数据
const loading = ref(false)
const actions = ref<Interaction[]>([])
const currentPage = ref(1)
const pageSize = ref(5) // 与后端默认值保持一致
const total = ref(0)
const todayActions = ref(120)
const favoriteActions = ref(45)
const detailVisible = ref(false)
const currentAction = ref<Interaction | null>(null)

// 新增相关
const addVisible = ref(false)
const addFormRef = ref()
const submitLoading = ref(false)
const addForm = reactive({
  userId: undefined as number | undefined,
  productId: undefined as number | undefined,
  type: undefined as number | undefined
})

// 表单验证规则
const addFormRules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number' as const, min: 1, message: '用户ID必须大于0', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请输入商品ID', trigger: 'blur' },
    { type: 'number' as const, min: 1, message: '商品ID必须大于0', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择行为类型', trigger: 'change' }
  ]
}

// 搜索表单
const searchForm = reactive({
  productName: '',
  type: undefined as number | undefined
})

// 获取行为列表
const loadActions = async () => {
  loading.value = true
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      productName: searchForm.productName || undefined
    }
    
    // 只有当选择了行为类型时才传递参数
    if (searchForm.type !== undefined) {
      params.type = searchForm.type
    }
    
    const res = await request.get('/interaction/list', { params }) as any
    
    console.log('Interaction API Response:', res)
    
    // 后端返回的是 PageView 对象
    if (res.data) {
      // 确保数据是数组
      const dataArray = Array.isArray(res.data.data) ? res.data.data : []
      actions.value = dataArray
      total.value = res.data.allRow || 0
    } else {
      actions.value = []
      total.value = 0
    }
    
    console.log('Actions after processing:', actions.value)
  } catch (error) {
    ElMessage.error('获取行为列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadActions()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    productName: '',
    type: undefined
  })
  currentPage.value = 1
  loadActions()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadActions()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadActions()
}

// 查看行为详情
const handleView = (row: Interaction) => {
  currentAction.value = row
  detailVisible.value = true
}

// 删除行为
const handleDelete = async (row: Interaction) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户${row.userId}对商品"${row.productName}"的${getActionTypeText(row.type)}记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/interaction/delete/${row.id}`)
    ElMessage.success('删除成功')
    // 重新获取分页数据
    loadActions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 新增行为
const handleAdd = () => {
  addVisible.value = true
  // 重置表单
  Object.assign(addForm, {
    userId: undefined,
    productId: undefined,
    type: undefined
  })
}

// 关闭新增对话框
const handleAddClose = () => {
  addVisible.value = false
  addFormRef.value?.resetFields()
}

// 提交新增
const handleSubmit = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    submitLoading.value = true
    
    const submitData = {
      userId: addForm.userId,
      productId: addForm.productId,
      type: addForm.type
    }
    
    await request.post('/interaction/add', submitData)
    ElMessage.success('新增成功')
    handleAddClose()
    // 重新获取分页数据
    loadActions()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('新增失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentAction.value = null
}

// 获取行为类型标签样式
const getActionTypeTag = (type: number) => {
  switch (type) {
    case 1: return 'success' // 收藏 - 绿色
    case 2: return 'info'    // 浏览 - 灰色
    case 3: return 'warning' // 想要 - 橙色
    default: return 'info'
  }
}

// 获取行为类型文本
const getActionTypeText = (type: number) => {
  switch (type) {
    case 1: return '收藏'
    case 2: return '浏览'
    case 3: return '想要'
    default: return '未知'
  }
}

// 初始化
onMounted(() => {
  // 确保数据是数组
  if (!Array.isArray(actions.value)) {
    actions.value = []
  }
  loadActions()
})
</script>

<style scoped lang="scss">
.actions-container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: $text-color;
    }
    
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 5px;
    align-items: center;
  }
}

.action-detail {
  .detail-item {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    
    label {
      width: 100px;
      font-weight: bold;
      color: $text-color;
    }
    
    span {
      flex: 1;
      color: $text-color-regular;
    }
  }
}
</style> 